import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin} from 'antd';
import routes from './routes';
import {newOrderValidator} from './validator';
import Return from '../common/Return';
import {injectIntl, language} from './intl';
import {FORM_OPTIONS, DATE_FORMAT, FORM_ROW_OPTIONS} from '../constants';
import {partOrderStatus, paymentType, partOrderPriceTerms,
    transportType, currency, proformaInvoiceStatus, stockRequirementStatus} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import PartSaleOrderSelectPanel from './PartSaleOrderSelectPanel';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {orderStatus} from './constants';

const partOrderStatusList = orderStatus.toList(language);
const FormItem = Form.Item;
export class PartSaleOrderPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        data: {},
        showPartSaleOrder: false
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data} = this.state;
        const isValid = newOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        this.props.onSubmit(data)
            .then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSelectPartSaleOrder = data => {
        this.setState({
            data: {
                partSaleOrderId: data.id,
                code: data.code,
                brandCode: data.brandCode,
                brandName: data.brandName,
                dealerCode: data.dealerCode,
                totalQuantity: data.totalQuantity,
                partOrderTypeName: data.partOrderTypeName,
                status: data.status,
                createTime: data.createTime,
                transportType: data.transportType,
                paymentType: data.paymentType,
                partOrderPriceTerms: data.partOrderPriceTerms,
                totalAmount: data.totalAmount,
                varietyNumber: data.varietyNumber,
                currency: data.currency,
                orderRemark: data.remark,
                piCode: data.piCode,
                piStatus: data.piStatus,
                requirementStatus: data.requirementStatus
            },
            hasOperat: true,
            showPartSaleOrder: false
        });
    }
    onClickPartSaleOrder = () => {
        this.setState({showPartSaleOrder: true});
    }
    onClosePartSaleOrder = () => {
        this.setState({showPartSaleOrder: false});
    }
    render() {
        const {data} = this.state;
        const {formatMessage} = this.props.intl;
        const validateOrderCode = !data.partSaleOrderId && this.state.isValidate ? 'error' : null;
        const validateOrderStatus = !data.orderStatus && this.state.isValidate ? 'error' : null;
        const validateRemark = data.remark && data.remark.length > 200 && this.state.isValidate ? 'error' : null;
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'partSaleOrderPanel.card.saleOrder',
                            defaultMessage: '销售订单信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.brandCode',
                                        defaultMessage: '品牌'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.partSaleOrderId ? `(${data.brandCode})${data.brandName}` : ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.dealerCode',
                                        defaultMessage: '总代号'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.code',
                                        defaultMessage: '订单编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateOrderCode}
                                    required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.code}
                                            onClickSearchBtn={this.onClickPartSaleOrder}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.partOrderTypeName',
                                        defaultMessage: '订单类型'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.partOrderTypeName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.status',
                                        defaultMessage: '状态'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(partOrderStatus, data.status)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.createTime',
                                        defaultMessage: '提报日期'
                                    })} {...FORM_OPTIONS.item} >
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.transportType',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(transportType, data.transportType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.varietyNumber',
                                        defaultMessage: '品种数'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.varietyNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.totalQuantity',
                                        defaultMessage: '订购数量'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.totalQuantity}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.totalAmount',
                                        defaultMessage: '总金额'
                                    })} {...FORM_OPTIONS.item} >
                                        {formatAmount(data.totalAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.paymentType',
                                        defaultMessage: '付款方式'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(paymentType, data.paymentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.partOrderPriceTerms',
                                        defaultMessage: '价格条款'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(partOrderPriceTerms, data.partOrderPriceTerms)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.piCode',
                                        defaultMessage: 'PI编号'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.piCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.piStatus',
                                        defaultMessage: 'PI状态'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(proformaInvoiceStatus, data.piStatus)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.requirementStatus',
                                        defaultMessage: '备货需求状态'
                                    })} {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(stockRequirementStatus, data.requirementStatus)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.column.orderRemark',
                                        defaultMessage: '订单备注'
                                    })} {...FORM_OPTIONS.item} >
                                        {data.orderRemark}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card title={formatMessage({
                            id: 'partSaleOrderPanel.card.delivery.title',
                            defaultMessage: '交货单目标状态'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.operation.orderStatus',
                                        defaultMessage: '备件订单状态'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateOrderStatus}
                                    required>
                                        <WrappedSelect
                                            name="orderStatus"
                                            value={data.orderStatus}
                                            options={partOrderStatusList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'partSaleOrderPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateRemark}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'partSaleOrderPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                    {
                        this.state.showPartSaleOrder &&
                        <PartSaleOrderSelectPanel
                            selectKey={data.code}
                            onCancel={this.onClosePartSaleOrder}
                            onSelect={this.onSelectPartSaleOrder} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

PartSaleOrderPanel.propTypes = {
    data: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    brands: PropTypes.array,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch, onSubmitOrder} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id,
            currency: item.currency
        })) : [];
        return brands;
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    brands: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onSubmitOrder(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(PartSaleOrderPanel));
